package chances.epg.data.taglib;

import javax.servlet.jsp.JspException;

import org.slf4j.Logger;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.entity.content.Channel;
import chances.epg.entity.content.Schedule;
import chances.epg.navigator.context.AccessContext;
import chances.epg.navigator.context.AccessContextUtils;

public class ContentTag extends QueryTag {
	private static final Logger logger = EpgLogFactory.getSystemLogger();

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private String code;
	private String type;

	@Override
	public int doEndTag() throws JspException {
		String contentType = this.type.toLowerCase();
		try {
			Object object = null;
			if ("vod".equals(contentType)) {
				object = this.getContentService().getProrgamByCode(this.code);
			} else if ("series".equals(contentType) || "series2".equals(contentType)) {
				object = this.getContentService().getSeriesByCode(this.code);
			} else if ("subject".equals(contentType)) {
				/* not support */
			} else if ("album".equals(contentType)) {
				object = this.getContentService().getAlbumByCode(this.code);
			} else if ("subjectpage".equals(contentType)) {
				object = this.getContentService().getSubjectPageByCode(this.code);
			} else if ("channel".equals(contentType)) {
				object = this.getChannelService().getChannelByCode(this.code);
			} else if ("schedule".equals(contentType)) {
				object = this.getChannelService().getScheduleByCode(this.code);
			} else if ("information".equals(contentType)) {
				object = this.getContentService().getInformationByCode(this.code);
			} else if ("link".equals(contentType)) {
				object = this.getContentService().getLinkByCode(this.code);
			} else {
				logger.error("ContentTag error,not support content type:{}", contentType);
			}
			this.setContent(object);
		} catch (Exception ex) {
			logger.error("ContentTag error", ex);
		}

		return super.doEndTag();
	}

	private void setContent(Object object) {
		AccessContext context = AccessContextUtils.getAccessContext(pageContext);
		if (null != context && object != null) {
			if (object instanceof Channel) {
				Channel channel = (Channel) object;
				String url = navigateUrlFactory.generateURL(context, channel);
				channel.setUrl(url);
				this.setResult(channel);
			} else if (object instanceof Schedule) {
				Schedule schedule = (Schedule) object;
				String url = navigateUrlFactory.generateURL(context, schedule);
				schedule.setUrl(url);
				this.setResult(schedule);
			} else {
				this.setResult(object);
			}
		}
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
}
